import { NextResponse, NextRequest } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// DELETE /api/notifications/[id] - 删除通知
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const notificationId = params.id;

    // 查找通知接收者记录
    const notificationRecipient = await prisma.notificationRecipient.findFirst({
      where: {
        notificationId,
        userId,
      },
    });

    if (!notificationRecipient) {
      return NextResponse.json({ error: '找不到通知' }, { status: 404 });
    }

    // 删除通知接收者关系
    await prisma.notificationRecipient.delete({
      where: {
        id: notificationRecipient.id,
      },
    });

    // 检查该通知是否还有其他接收者
    const otherRecipients = await prisma.notificationRecipient.findFirst({
      where: {
        notificationId,
      },
    });

    // 如果没有其他接收者，删除通知本身
    if (!otherRecipients) {
      await prisma.notification.delete({
        where: {
          id: notificationId,
        },
      });
    }

    return new NextResponse(null, { status: 204 });
  } catch (error) {
    console.error('删除通知失败:', error);
    return NextResponse.json(
      { error: '删除通知时出错' },
      { status: 500 }
    );
  }
} 